/**
 * @author Michael,Aug 14, 2012
 *
 */
package com.tm.util;

import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;

import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

import com.util.BasePojo;

/**
 * @author Michael
 *
 */
public class PojoUpdateInterceptor extends EmptyInterceptor{

	private static final long	serialVersionUID	= 1L;

	@Override
	public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
		this.setPojoProperties(entity, id, state, propertyNames);
	}

	@Override
	public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
		return this.setPojoProperties(entity, id, currentState, propertyNames);
	}

	@Override
	public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
		return this.setPojoProperties(entity, id, state, propertyNames);
	}
	
	

	private boolean isBasePojoSun(Class c){
		if(c.getSuperclass() != null && c.getSuperclass().getSimpleName().equals(BasePojo.class.getSimpleName())){
			return true;
		}else{
			return false;
		}
	}
	
	private boolean setPojoProperties(Object entity, Serializable id, Object[] state, String[] propertyNames){
		boolean ret = false;
		if(isBasePojoSun(entity.getClass())){
			if(id == null){
				//save
				boolean createTimeSet = false;
				boolean deletedSet = false;
				for (int i = propertyNames.length -1; i >=0; i--) {
					if(propertyNames[i].equals("createdTime")){
						if(state[i]  == null){
							state[i] = new Timestamp(new Date().getTime());
						}
						createTimeSet = true;
					}else if(propertyNames[i].equals("deleted")){
						if(state[i] == null){
							state[i] = false;
						}
						deletedSet = true;
					}
					if(createTimeSet && deletedSet){
						ret = true;
						break;
					}
				}
			}else{
				//update 
				for (int i = propertyNames.length-1; i >=0 ; i--) {
					if(propertyNames[i].equals("latestModify")){
						state[i] = new Timestamp(new Date().getTime());
						break;
					}
				}
			}
		}else{
			ret = true;
		}
		return ret;
	}
	
	

}
